using System;
using System.Windows.Forms;
using Core;
using SpaceTrader.Core;

namespace SpaceTrader.WinUI
{
    public partial class ConsoleWindow : Form, IController
    {
        protected Game mGame;

        public ConsoleWindow()
        {
            InitializeComponent();
        }

        #region IController Members

        public Game Game
        {
            get { return mGame; }
            set { mGame = value; }
        }

        public void Render()
        {
            UpdateLog(Logger.Instance().LogFile);
        }

        #endregion

        private void UpdateLog(string Log)
        {
            if (LogViewer.InvokeRequired)
            {
                SetLogText d = UpdateLog;
                try
                {
                    Invoke(d, new object[] {Log});
                }
                catch (ObjectDisposedException e)
                {
                    Logger.Instance().Log("Console window disposed during update.\r\n" + e, LogLevel.Debug);
                }
            }
            else
                LogViewer.Text = Log;
        }

        private void ConsoleWindow_FormClosing(object sender, FormClosingEventArgs e)
        {
            e.Cancel = true;
            Hide();
        }

        private void ExecuteButton_Click(object sender, EventArgs e)
        {
            char[] splitter = {' '};

            try
            {
                string[] Arguments = CommandText.Text.Split(splitter);
                string Command = Arguments[0];
                switch (Command)
                {
                    case "GetStatus":
                        Logger.Instance().Log(Game.Objects[Int16.Parse(Arguments[1])].ToString(), LogLevel.Debug);
                        break;

                    case "GetPoly":
                        Logger.Instance().Log(Game.Objects[Int16.Parse(Arguments[1])].GetPolygon().ToString(),
                                              LogLevel.Debug);
                        break;
                }
            }
            catch (Exception ex)
            {
                Logger.Instance().Log("Exception!\r\n" + ex, LogLevel.Error);
            }
        }

        #region Nested type: SetLogText

        private delegate void SetLogText(string Text);

        #endregion
    }
}